package org.developer.websocketserver.handler;

import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.developer.websocketserver.context.ServerContext;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
@ChannelHandler.Sharable
@Slf4j
public class CloseServerHandler extends SimpleChannelInboundHandler<CloseWebSocketFrame> {

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 用户退出后向全部Channel发送下线消息
        ServerContext.channelGroup.writeAndFlush(
                new TextWebSocketFrame(
                        String.format("[服务器]\t用户：%s 离开聊天室！\n", ctx.channel().remoteAddress())));
        // 移除
        ServerContext.channelGroup.remove(ctx.channel());

        log.info("[断开连接]: 当前连接数={}",ServerContext.channelGroup.size());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CloseWebSocketFrame closeWebSocketFrame) throws Exception {

        Channel currentChannel = ctx.channel();
        InetSocketAddress address = (InetSocketAddress) currentChannel.remoteAddress();
        String ip = address.getAddress().getHostAddress();
        int port = address.getPort();
        log.info("有client断开连接,[ip]:{},[port]:{}",ip,port);

        ChannelFuture close = currentChannel.close();

        log.info("close={}",close);
    }
}
